import { defineStore } from "pinia";
import { fetchMenu } from "@/apis/menu.js";
import { ref } from 'vue';
import { useRouter } from 'vue-router';

export const useMenuStore = defineStore("menuStore", () => {
    const menu = ref([]); // 用于存储菜单数据
    const router = useRouter();

    // 注册路由的方法
    const registerRoutes = (menuItems) => {
        const processMenu = (items) => {
            items.forEach(item => {
                if (item.children && item.children.length > 0) {
                    processMenu(item.children);
                    return;
                }
                
                if (!router.hasRoute(item.name)) {
                    const relativePath = item.path.split('/').pop();
                    router.addRoute('InfoPage', {
                        path: relativePath,
                        name: item.name,
                        component: () => import(`@/pages/InfoPage/views/${item.name}.vue`),
                    });
                }
            });
        };
        processMenu(menuItems);
    };

    const loadMenu = async () => {
        await fetchMenu().then(res => {
            const processedMenu = res.map(item => {
                if (item.name === 'InfoPage') {
                    return { ...item, title: '信息管理' };
                }
                return item;
            });
            menu.value = processedMenu; // 更新菜单数据
            registerRoutes(processedMenu); // 注册动态路由
        });
    };

    return { menu, loadMenu };
});